package com.ctgu.tengyun.config;

import com.ctgu.tengyun.bean.convert.FileConvert;
import com.ctgu.tengyun.exception.TengyunRuntimeException;
import com.ctgu.tengyun.manager.UserRoleScheduleManager;
import com.ctgu.tengyun.util.RSAEncrypt;
import com.ctgu.tengyun.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Created by liaoweizhi on 2019/7/20.
 */
@Configuration
public class ResourceConfig implements WebMvcConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(ResourceConfig.class);

    private final static String RSA_TXT_INITIALIZATION = "rsaTxtInitialization";

    @Value("${file.mapping.path}")
    private String mappingPath;
    @Value("${file.win.path}")
    private String winPath;
    @Value("${file.linux.path}")
    private String linuxPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {  //如果是Windows系统
            registry.addResourceHandler(mappingPath).
                    addResourceLocations(winPath);
        } else {//linux和mac系统
            registry.addResourceHandler(mappingPath).
                    addResourceLocations(linuxPath);
        }
    }

    @Bean
    public UploadConfig uploadConfig(@Value("${base.dir}") String baseDir,
                                     @Value("${tmp.store.dir}") String tmpStoreDir,
                                     @Value("${util.upload.tmp.dir}") String utilUploadTmpDir,
                                     @Value("${max.size.upload}") Long sizeThreshold,
                                     @Value("${user.max.size.upload}") Long userUploadMaxSize,
                                     @Value("${file.max.size.upload}") Long fileSizeThreshold,
                                     @Value("${file.path.prefix}") String filePathPrefix
    ) {
        UploadConfig uploadConfig = new UploadConfig();
        uploadConfig.setBaseDir(baseDir);
        uploadConfig.setTmpStoreDir(tmpStoreDir);
        uploadConfig.setUtilUploadTmpDir(utilUploadTmpDir);
        uploadConfig.setSizeThreshold(sizeThreshold);
        uploadConfig.setUserUploadMaxSize(userUploadMaxSize);
        uploadConfig.setFileSizeThreshold(fileSizeThreshold);

        FileConvert.setFilePathPrefix(filePathPrefix);
        return uploadConfig;
    }

    @Bean(name = RSA_TXT_INITIALIZATION)
    public Boolean rsaKeyInitialization(@Value("${rsa.encrypt.publickey}") String publicKey,
                                        @Value("${rsa.encrypt.privatekey}") String privateKey) throws Exception {
        if (StringUtils.isEmpty(publicKey)) {
            throw new TengyunRuntimeException("publicKey not found");
        }

        if (StringUtils.isEmpty(privateKey)) {
            throw new TengyunRuntimeException("privateKey not found");
        }

        RSAEncrypt.setPublicKey(publicKey);
        RSAEncrypt.setPrivateKey(privateKey);

        String testSource = "test";
        String encryptStr = RSAEncrypt.encrypt(testSource);
        String decryptStr = RSAEncrypt.decrypt(encryptStr);
        boolean initStatus = testSource.equals(decryptStr);
        logger.info("rsa init status: " + initStatus);
        if (!initStatus) {
            throw new TengyunRuntimeException(publicKey + " or " + privateKey + ", config error");
        }

        return Boolean.TRUE;
    }

    @Bean(initMethod = "init", destroyMethod = "stop")
    public UserRoleScheduleManager userRoleScheduleManager() {
        UserRoleScheduleManager manager = new UserRoleScheduleManager();
        manager.setRunIntervalSeconds(300); //用户角色缓存刷新时间

        return manager;
    }

}
